'use strict';
const mongoose = require('mongoose');

let schema = new mongoose.Schema({

});

schema.statics = {

};

schema.methods={
    // 新增统计
    list:async function(options={minTimeTick:0,maxTimeTick:0}){
        let CensusModel=mongoose.models['Census'];
        let now=new Date().getTime();
        let query={
            group:'渠道统计',
            timeTick:{$gte:now-86400000,$lt:now},
            type:options.self._id.toString()
        };
        if(!!options.minTimeTick){
            query.timeTick.$gte=parseInt(options.minTimeTick);
        }
        if(!!options.maxTimeTick){
            query.timeTick.$lt=parseInt(options.maxTimeTick);
        }
        let census=await CensusModel.find(query);
        //channels.sort((a,b)=>{return b.sort-a.sort;});
        return census;
    },
    // 留存统计
    remainList:async function(options={group:'',type:'',minTimeTick:0,maxTimeTick:0}){
        let CensusModel=mongoose.models['Census'];
        let now=new Date().getTime();
        let groups = ['次日留存','七日留存'];
        let query={
            group:{$in: groups},
            timeTick:{$gte:now-86400000,$lt:now},
            type:options.self._id.toString()
        };
        if(!!options.group){
            groups = options.group.split(',');
            query.group={$in: groups};
        }
        // if(!!options.type){
        //     query.type=options.type;
        // }
        if(!!options.minTimeTick){
            query.timeTick.$gte=parseInt(options.minTimeTick);
        }
        if(!!options.maxTimeTick){
            query.timeTick.$lt=parseInt(options.maxTimeTick);
        }
        let census=await CensusModel.find(query);
        //channels.sort((a,b)=>{return b.sort-a.sort;});
        let censusRes = new Array(groups.length);
        for(let i=0;i<censusRes.length;i++){
            censusRes[i] = [];
        }
        for(let i=0;i<census.length;i++){

            census[i] = census[i]._doc;
            if(census[i].setCount > 0){
                census[i].count = census[i].setCount;
            }
            // 昨天数据10点后更新
            let time = new Date().toLocaleDateString();
            let tenHours = new Date(time + ' 10:00:00').getTime();
            if((census[i].timeTick > new Date(time + ' 0:0:0').getTime()) && (new Date().getTime() < tenHours)){
                console.log('当前时间小于当天10点钟');
                census[i].count = 0;
            }

            censusRes[groups.indexOf(census[i].group)].push(census[i]);
        }
        return censusRes;
    },
};

module.exports = schema;